package com.hn658.base.message.publish.business.impl;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.hn658.base.message.common.enums.NotifyType;
import com.hn658.base.message.eventbus.event.Event;
import com.hn658.base.message.eventbus.event.groupchat.GroupMsgEvent;
import com.hn658.base.message.eventbus.event.singlechat.SingleMsgEvent;
import com.hn658.base.message.eventbus.event.systemchat.SystemMsgEvent;
import com.hn658.base.message.managermq.send.AbstractMessageSend;
import com.hn658.base.message.notification.msg.business.IMessageManager;
import com.hn658.base.message.notification.msg.entity.MessageEO;
import com.hn658.base.message.notification.util.NotifyIdHelper;
import com.hn658.base.message.publish.business.IEventPublishManager;
import com.hn658.base.message.publish.exception.PublicException;
import com.hn658.framework.logging.Logger;
import com.hn658.framework.logging.LoggerFactory;
import com.hn658.framework.logging.enums.LogCategory;

/**
 * Created by baihai on 2015/11/25.
 */
@Service
public class MQEventPublishManager extends AbstractMessageSend implements IEventPublishManager{

    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(MQEventPublishManager.class);

	@Autowired
	private IMessageManager messageManager;

    /**
     * 发布系统消息
     * @param event
     */
    @Override
    public void publishSystemMsgEvent(final SystemMsgEvent event) {
    	MessageEO msg = event.getMessage();
        String notifyId = NotifyIdHelper.getNotifyId(msg.getFromUid(),null
                   , NotifyType.SystemNotify.getValue(),event.getAppId());
        msg.setNotifyId(notifyId);
        if(event.getIsNeedSave()){
        	//保存私信
        	messageManager.save(msg);        	
        }
        this.publish(event);
    }
    
    /**
     * 发布单聊消息
     * @param event
     */
    @Override
    public void publishSingleMsgEvent(final SingleMsgEvent event) {
        MessageEO msg = event.getMessage();
        String notifyId = NotifyIdHelper.getNotifyId(msg.getFromUid(),msg.getToUid()
                   , NotifyType.SingleChat.getValue(),event.getAppId());
        msg.setNotifyId(notifyId);
        if(event.getIsNeedSave()){
        	//保存私信
        	messageManager.save(msg);        	
        }
        this.publish(event);
    }
    
    /**
     * 发布群聊消息
     * @param event
     */
    @Override
    public void publishGroupMsgEvent(final GroupMsgEvent event) {
    	MessageEO msg = event.getMessage();
        String notifyId = NotifyIdHelper.getNotifyId(msg.getFromUid(),null
                   , NotifyType.GroupChat.getValue(),event.getAppId());
        msg.setNotifyId(notifyId);
        if(event.getIsNeedSave()){
        	//保存私信
        	messageManager.save(msg);        	
        }
        this.publish(event);
    }

    private void publish(final Event event){
    	logger.debug(LogCategory.SYSTEM,"EventBus Manager推送消息:{}", event);

        try {
        	
            this.getJmsTemplate(event).send(this.getDestination(event), new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    logger.debug("JMS send event message:{}", jsonMapper.toJson(event));
                    return session.createTextMessage(jsonMapper.toJson(event));
                }
            });
        } catch (Exception ex) {
            logger.error("EventBus 发送JMS信息时发生异常:{}", ExceptionUtils.getStackTrace(ex));
            throw new PublicException(PublicException.NoRegisterThisMq);
        }
    }

    public JmsTemplate getJmsTemplate(Event event) {

        // 获取对应的jms模板
        return getJmsTemplate(event.getAppId(),event.getPriority().getValue());
    }

    public Destination getDestination(Event event) {

        // 获取对应通道
        return getDestination(event.getAppId(),event.getPriority().getValue());
    }



}
